/**
 * Magic Input Auto Complete Plugin 1.0
 * Author: Mac_J@boarsoft.com
 * Need: core.js
 */
mac.input_autoCp = function(self, cfg) {
	var sc = 'selected', hc = 'hover', bd = self.next();
	if (cfg.boxHeight) {
		bd.height(cfg.boxHeight);
	}
	bd.mousedown(function(e) {
		e.stopPropagation();
		return false;
	});
	self.close = function() {
		self.isOpen = false;
		bd.hide();
	}
	self.open = function() {
		self.isOpen = true;
		var w = cfg.boxWidth || self.width()
			, p = self.position(), bt = cfg.boxTop, bl = cfg.boxLeft;
		bt = (bt || bt == 0) ? bt : (cfg.height + 2);
		bl = (bl || bl == 0) ? bl : 1;
		bd.css({
			top : p.top + bt,
			left : p.left + bl
		});
		bd.width(Math.max(w, cfg.boxMinWidth || w)).show();
		if (cfg.onOpen)
			cfg.onOpen();
		$(document).one('mousedown', self.close);
	}
	self.loadData = function(dd) {
		bd.empty();
		if (!dd || !dd.length)
			return;
		$.each(dd, function(i, r) {
			var a = $('<div class="tr"></div>').append(r);
			a.mousedown(function() {
				self.val(r);
				self.close();
			}).hover(function() {
				bd.children().removeClass(hc);
				$(this).addClass(hc);
			}, function() {
				$(this).removeClass(hc);
			});
			bd.append(a);
		});
		if (cfg.onLoad)
			cfg.onLoad(self, dd);
	}
	var ldr = cfg.loader;
	if (cfg.data) {
		self.loadData(cfg.data);
	} else if (ldr && ldr.url) {
		$.post(ldr.url, ldr.params, function(data) {
			var ro = mac.eval(data);
			if (ro.success) {
				ro = ro.data;
				self.loadData(ro.list);
			}
		});
	}
	self.keydown(function(e) {
		var k = e.keyCode, op = self.isOpen;
		var rs = bd.children('.tr'), v = ':visible';
		switch (k) {
		case 9: // TAB
			self.close();
			break;
		case 38: // UP
		case 40: // DOWN
			var x, d = (k == 40);
			if (!op && d)
				self.open();
			rs = rs.filter(v);
			var h = rs.filter('.' + hc), s = rs.filter('.' + sc);
			rs.removeClass(hc);
			var hx = (d ? h.nextAll(v) : h.prevAll(v)).first();
			var sx = (d ? s.nextAll(v) : s.prevAll(v)).first();
			if (h.length + s.length == 0 || hx.length + sx.length == 0) {
				x = (d ? rs.first() : rs.last());
			} else if (hx.length) {
				x = hx;
			} else if (sx.length && op && !h.length) {
				x = sx;
			} else if (s.length && !op) {
				x = s;
			} else {
				x = (d ? rs.first() : rs.last());
			}
			x.addClass(hc);
			return false;
		case 13:// RETURN
			if (op) {
				bd.children('.' + hc).mousedown();
			}
			break;
		case 27:// ESC
			self.close();
			break;
		default:
			var v = self.val(), lt = bd.children();
			if (!v || v.length < (cfg.minChars || 4)) {
				lt.show();
				break;
			}
			lt.each(function(n, c) {
				var ec = $(c), x = ec.text();
				ec.toggle(x && x.indexOf(v) > -1);
			});
			if (!self.isOpen)
				self.open();
		}
		return true;
	});
	return self;
}